const router = require('koa-router')();
const gewuyanyiDB = require('../models/gewuyanyiDB.js');

const fs = require('fs'),
      path = require('path');

const Buffer = require('buffer').Buffer;

router.prefix('/api/');
class allData {
  constructor(){
    this.code = 0;
    this.msg = 'ok';
    this.count = 0;
    this.data = '';                     
  }
};

// 用户数据的获取
router.get('/getUsers',async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getUsers();
});

// 新用户的注册
router.post('/registerUsers',async(ctx,next)=>{
  const users = await gewuyanyiDB.getUsers();
  const user = new allData();
  for(let i = 0; i<users.data.length; i++){
    if(ctx.request.body.username == users.data[i].user_name){
      user.data = {
        'error':'此用户名已被注册，请更改用户名'
      }
      ctx.body = user;
      return;
    }
  }
  await gewuyanyiDB.insertUsers(ctx.request.body.username,ctx.request.body.password);
  user.data = {
    'user_name':ctx.request.body.username,
    'user_password':ctx.request.body.password,
    'gwyy':'恭喜您注册成功'
  }
  ctx.body = user;
});

// 用户的登录
router.post('/usersSignIn',async(ctx,next)=>{
  const {user_name,user_password} = ctx.request.body;
  const res = await gewuyanyiDB.getUsers();
  var num = 0;
  const user = new allData();
  for(let i = 0; i<res.data.length; i++){
    if(user_name == res.data[i].user_name && user_password == res.data[i].user_password){
      user.data = {
        'user_name':user_name,
        'user_password':user_password,
        'gwyy':'AAAAAA'
      };
      ctx.body = user;
      break;
    } else{
      num++;
    }        
  }
  if(num == res.data.length){
    user.data = {
      'error':'用户名或密码错误'
    };
    ctx.body = user;
  }
});

// 指定用户数据的删除
router.delete('/delUsers:user_id',async(ctx,next)=>{
  const {user_id} = ctx.params;
  await gewuyanyiDB.delUsers(user_id);
  ctx.body = '删除成功';
});

// 指定用户数据的更新
router.post('/updateUser:user_id',async (ctx,next)=>{
  const file = ctx.request.files.file;
  if(!(/image\/\w/.test(file.mimetype))){
    ctx.body = {
      'error':'上传的文件非图片类型，请重新上传'
    }
    return;        
  }
  const reader = fs.createReadStream(file.filepath);
  let filePath = path.join(__dirname,'../public/images/')+`${file.originalFilename}`;
  const writer = fs.createWriteStream(filePath);
  reader.pipe(writer);
  const {user_name,user_password,user_introduction,user_design_cost,user_style,user_cultural_experience,user_curriculum_vitae} = ctx.request.body;
  const users = await gewuyanyiDB.getUsers();
  const user = new allData();
  for(let i=0; i<users.data.length; i++){
    if(user_name == users.data[i].user_name){
      user.data = {
        'error':'此用户名已存在！'
      }
      ctx.body = user;
      return;
    }
  }
  const user_head_portrait = file.originalFilename;
  const {user_id} = ctx.params;
  ctx.body = await gewuyanyiDB.updateUsers(user_id,user_name,user_password,user_introduction,user_head_portrait,user_design_cost,user_style,user_cultural_experience,user_curriculum_vitae);
});

// 管理员的后台登录
router.post('/adminsSignIn', async(ctx,next)=>{
  const {admins_name,admins_password} = ctx.request.body;
  const res = await gewuyanyiDB.getAdmins();
  var num = 0;
  const admin = new allData();
  for(let i = 0; i<res.data.length; i++){
    if(admins_name == res.data[i].admins_name && admins_password == res.data[i].admins_password){
      admin.data = {
        'admins_name':admins_name,
        'admins_password':admins_password,
        'gwyy':'aaaaaa'
      };
      ctx.body = admin;
      break;                      
    } else{
      num++;
    }
  }
  if(num == res.data.length){
    admin.data = {
      'error':'用户名或密码错误'
    };
    ctx.body = admin;                
  }
});

// 用户设计数据的获取
router.get('/getUserDesignDatas',async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getUserDesignDatas();
});

// 用户设计数据的上传
router.post('/postUserDesignDatas',async(ctx,next)=>{
  const {user_id,design_name,design_content,design_image} = ctx.request.body;
  ctx.body = await gewuyanyiDB.insertUserDesignDatas(user_id,design_image,design_name,design_content);
});

// 用户设计数据的删除
router.delete('/delUserDesignDatas:design_id',async(ctx,next)=>{
  const {design_id} = ctx.params;
  await gewuyanyiDB.delUserDesignDatas(design_id);
  ctx.body = "删除成功";
});

// 模型素材的获取
router.get('/getModelDatas', async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getModelDatas();
});

// 模型素材的删除
router.delete('/delModelDatas/:model_id', async(ctx,next)=>{
  var {model_id} = ctx.params;
  ctx.body = await gewuyanyiDB.delModelDatas(model_id);
});

// 绘制素材的获取
router.get('/getDrawDatas', async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getDrawDatas();
});

// 绘制素材的删除
router.delete('/delDrawDatas/:draw_id', async(ctx,next)=>{
  var {draw_id} = ctx.params;
  ctx.body = await gewuyanyiDB.delDrawDatas(draw_id);
});

// 灵感关注数据的获取
router.get('/getInspirationAttentionDatas/:user_inspiration_id',async(ctx,next)=>{
  const {user_inspiration_id} = ctx.params;
  ctx.body = await gewuyanyiDB.getInspirationAttentionDatas(user_inspiration_id);
});

// 灵感关注数据的插入
router.post('/postInspirationAttentionDatas',async(ctx,next)=>{
  const {user_inspiration_id,user_id,design_id} = ctx.query;
  ctx.body = await gewuyanyiDB.insertInspirationAttentionDatas(user_inspiration_id,user_id,design_id);
});

// 灵感关注数据的删除
router.delete('/delInspirationAttentionDatas',async(ctx,next)=>{
  const {user_inspiration_id,design_id,user_id} = ctx.query;
  await gewuyanyiDB.delInspirationAttentionDatas(user_inspiration_id,design_id,user_id);
  ctx.body = "删除成功";
});

// 创作资源的获取
router.get('/getCreationResourcesDatas', async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getCreationResourcesDatas();
});

// 创作资源的删除
router.delete('/delCreationResourcesDatas/:create_id', async(ctx,next)=>{
  var {create_id} = ctx.params;
  ctx.body = await gewuyanyiDB.delCreationResourcesDatas(create_id);
});

// 轮播图的获取
router.get('/getShowDatas', async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getShowDatas();
});

// 产品征集博物馆信息的获取
router.get('/getProductsCollectionMuseumDatas', async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getProductsCollectionMuseumDatas();
});

// 产品征集比赛活动的获取
router.get('/getProductsCollectionMatchDatas', async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getProductsCollectionMatchDatas();
});

// 帮助中心数据的获取
router.get('/getHelpCenterDatas',async(ctx,next)=>{
  const {con_title} = ctx.query;
  ctx.body = await gewuyanyiDB.getHelpCenterDatas(con_title);
});

// 用户上传素材的获取
router.get('/getUserUploadDatas', async(ctx,next)=>{
  ctx.body = await gewuyanyiDB.getUserUploadDatas();
  //ctx.body = `<!DOCTYPE html>
  //<html>
  //<head>
    //<meta charset="UTF-8">
    //<title>Document</title>
  //</head>       
  //<body>
    //<form action="/api/user_upload_datas" enctype="multipart/form-data" method="post">
      //<input type="file" name="file" multiple="multiple" accept=".png, .jpg, .jpeg, .gif, .bmp">
      //<input type="submit">
    //</form>
  //</body>
  //</html>`;
});


// 用户上传素材
router.post('/postUserUploadDatas', async(ctx, next)=>{
  const files = ctx.request.files.file;
  //console.log(files.length);

  if(files.length == undefined ){ // 单张的上传
    const reader = fs.createReadStream(files.filepath);
    const upload_url = path.join(__dirname,'../public/images/')+`${files.originalFilename}`;
    const writer = fs.createWriteStream(upload_url);
    reader.pipe(writer);

    const upload_image = files.originalFilename;

    var {user_id} = ctx.request.body;
    ctx.body = await gewuyanyiDB.addUserUploadDatas(user_id,upload_image);
  } else{ // 多张的上传
    files.map(async(file)=>{
      const reader = fs.createReadStream(file.filepath);
      const upload_url = path.join(__dirname,'../public/images/')+`${file.originalFilename}`;
      const writer = fs.createWriteStream(upload_url);
      reader.pipe(writer);

      const upload_image = file.originalFilename;

      var {user_id} = ctx.request.body;
      ctx.body = await gewuyanyiDB.addUserUploadDatas(user_id,upload_image);
    })
  }
});

// 用户上传素材的删除
router.delete('/delUserUploadDatas/:upload_id', async(ctx,next)=>{
  var {upload_id} = ctx.params;
  ctx.body = await gewuyanyiDB.delUserUploadDatas(upload_id);
});

//提交到后端的图片base64数据
router.post('/postUrl',async(ctx,next)=>{
  const {url} = ctx.request.body;
  const data = Buffer.from(url,'base64');
  //console.log(data);
  let filePath = path.join(__dirname,'../public/images/')+'mtl.png';
  //console.log(filePath);
  fs.writeFile(filePath,data,err=>{
    if(err){
      console.log(err);
    }
  });
});

module.exports = router;
